package com.h819.core.file.pdf.pdfbox;

import org.apache.log4j.Logger;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.util.PDFTextStripper;

import java.io.*;

/**
 * @Title: PDFToTxt.java
 * @Description: TODO(提取 PDF 文件的文本内容。不能做 OCR,OCR 是图片文字识别。 )
 * @author H819
 * @date 2011-6-25
 * @version V1.0
 */

public class PDFToTxt {

	private static Logger log = Logger.getLogger(PDFToTxt.class);

	private PDDocument document = null;

	public PDFToTxt(File pdfSource) {
		try {
			document = PDDocument.load(pdfSource);

			if (document.isEncrypted()) {

				log.info(pdfSource + " isEncrypted.");

				return;
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.info(pdfSource + "does not exist.");
			e.printStackTrace();
		}
	}

	/**
	 * 提取 pdf 文本内容到指定文件
	 * 
	 * @param txtDesc
	 *            文本内容文件，txt 格式
	 * @throws IOException
	 */
	public void getPdfText(File txtDesc) throws IOException {
		PDFTextStripper stripper = new PDFTextStripper();
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				txtDesc));
		BufferedWriter bw = new BufferedWriter(osw);
		stripper.setShouldSeparateByBeads(true);
		stripper.setStartPage(2);
		stripper.setEndPage(3);
		stripper.writeText(document, bw);
		bw.close();
		document.close();
	}

}
